// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//  World_of_Indicators



//@version=5
indicator('Trading Beast V2.0 by World_Of_Indicators', 'Trading Beast V2.1 by World_Of_Indicators', overlay=true, max_bars_back=500, max_lines_count=500, max_labels_count=500)

///////////////////////////////////

//////////////////////////////////

//?--- Groups Setup ---?

gsrc     = 'SOURCE SETUP'
gichi    = 'ICHIMOKU SETTINGS'
gsr      = 'SUPPORTS/RESISTANCES SETTINGS'
gpsylvl  = 'PSYCHOLOGICAL LEVELS'
gadvset  = 'ADVANCED SETTINGS'
gvosc    = 'VOLUME OSCILLATOR SETTINGS'
gvrindex = 'RELATIVE VOLUME STRENGTH INDEX SETTINGS'
gatr     = 'VOLATILITY SETTINGS'
gbarcol  = 'BAR COLOR SETTINGS'
gtable   = 'PANEL SETTINGS'

//?--- Constant String Declaration ---?

string obvstr = 'On Balance Volume'
string cvdstr = 'Cumulative Volume Delta'
string pvtstr = 'Price Volume Trend'

//?--- Inputs ---?

i_src           = input.source(close, 'Source',                                                                                  group=gsrc)
i_altsrc        = input.string('(close > open ? high : low)', 'Alternative Source',                        options=['Default Source', '(open + close +3 * (high + low)) / 8', 'close + high + low -2 * open', '(close +5 * (high + low) -7 * (open)) / 4', '(open + close +5 * (high + low)) / 12', '(close > open ? high : low)', 'Heiken-Ashi'], group=gsrc)
i_uha           = input(true,                                 'Use Volume Heikin Ashi?',                                         group=gsrc)
i_wmas          = input.bool(true,                            'Weighted Moving Average Smoothing?',                              group=gsrc)
i_showlabels    = input.bool(false,                            'Show Labels?',                                                    group=gichi)
i_showprice     = input.bool(false,                            'Show Tenkan-Sen/kijun-Sen Price Labels?',                         group=gichi)
i_showtenkan    = input.bool(true,                            'Tenkan-Sen',                                                      group=gichi, inline='tenkan')
i_tenkancolor   = input.color(color.new(#007FFF, 0),        '',                                                                group=gichi, inline='tenkan')
i_tkminlen      = input.int(9,                                'Tenkan Min Length',                         minval=1,             group=gichi, inline='tenkanlength')
i_tkmaxlen      = input.int(30,                               'Tenkan Max Length',                         minval=1,             group=gichi, inline='tenkanlength')
i_tkdynperc     = input.float(96.85,                          'Tenkan Dynamic Length Adaptive Percentage', minval=0, maxval=100, group=gichi) / 100.0
i_tkvolsetup    = input.bool(true,                            'Volume',                                                          group=gichi, inline='tenkanfilter')
i_tkatrsetup    = input.bool(true,                            'Volatility',                                                      group=gichi, inline='tenkanfilter')
i_tkchfilter    = input.bool(true,                            'Chikou Trend Filter',                                             group=gichi, inline='tenkanfilter')
i_showkijun     = input.bool(true,                            'Kijun-Sen',                                                   group=gichi, inline='kijun')
i_kijuncolor    = input.color(color.new(#FF0016, 0),        '',                                                                group=gichi, inline='kijun')
i_showkjhlabels = input.bool(false,                            'Show Hidden Kijun-Sen Labels?',                                   group=gichi)
i_showkjhsr     = input.bool(false,                           'Show Hidden Kijun-Sen Supports/Resistances?',                     group=gichi)
i_kjminlen      = input.int(20,                               'Kijun Min Length',                          minval=1,             group=gichi, inline='kijunlength')
i_kjmaxlen      = input.int(60,                               'Kijun Max Length',                          minval=1,             group=gichi, inline='kijunlength')
i_kjdynperc     = input.float(96.85,                          'Kijun Dynamic Length Adaptive Percentage',  minval=0, maxval=100, group=gichi) / 100.0
i_kjdivider     = input.int(1,                                'Kijun Divider Tool',                        minval=1, maxval=4,   group=gichi)
i_kjvolsetup    = input.bool(true,                            'Volume',                                                          group=gichi, inline='kijunfilter')
i_kjatrsetup    = input.bool(true,                            'Volatility',                                                      group=gichi, inline='kijunfilter')
i_kjchfilter    = input.bool(true,                            'Chikou Trend Filter',                                             group=gichi, inline='kijunfilter')
i_showchikou    = input.bool(true,                            'Chikou Span',                                                     group=gichi)
i_chbearcol     = input.color(color.new(#FF0016, 0),        'Bear',                                                            group=gichi, inline='chikoucolor')
i_chbullcol     = input.color(color.new(#459915, 0),        'Bull',                                                            group=gichi, inline='chikoucolor')
i_chconsocol    = input.color(color.new(#FF9800, 0),        'Consolidation',                                                   group=gichi, inline='chikoucolor')
i_chminlen      = input.int(26,                               'Chikou Min Length',                         minval=1,             group=gichi, inline='chikoulength')
i_chmaxlen      = input.int(50,                               'Chikou Max Length',                         minval=1,             group=gichi, inline='chikoulength')
i_chdynperc     = input.float(96.85,                          'Chikou Dynamic Length Adaptive Percentage', minval=0, maxval=100, group=gichi) / 100.0
i_chfiltper     = input.int(25,                               'Chikou Filter Period',                      minval=1,             group=gichi)
i_chlb          = input.int(50,                               'Chikou Filter Percentage Lookback',         minval=1, maxval=89,  group=gichi)
i_chvolsetup    = input.bool(true,                            'Volume',                                                          group=gichi, inline='chikoufilter')
i_chatrsetup    = input.bool(true,                            'Volatility',                                                      group=gichi, inline='chikoufilter')
i_chtfilter     = input.bool(true,                            'Chikou Trend Filter',                                             group=gichi, inline='chikoufilter')
I_ska           = input.bool(true,                            'Senkou-Span A',                                                   group=gichi, inline='senkou')
I_skb           = input.bool(true,                            'Senkou-Span B',                                                   group=gichi, inline='senkou')
I_skbear        = input.color(color.new(#FF0016, 0),        'Bear',                                                            group=gichi, inline='senkoucolor')
I_skbull        = input.color(color.new(#459915, 0),        'Bull',                                                            group=gichi, inline='senkoucolor')
I_skconso       = input.color(color.new(#CED7DF, 0),        'Consolidation',                                                   group=gichi, inline='senkoucolor')
I_skminlen      = input.int(50,                               'Senkou-Span Min Length',                    minval=1,             group=gichi, inline='senkoulength')
I_skmaxlen      = input.int(120,                              'Senkou-Span Max Length',                    minval=1,             group=gichi, inline='senkoulength')
I_skperc        = input.float(96.85,                          'Senkou Dynamic Length Adaptive Percentage', minval=0, maxval=100, group=gichi) / 100.0
I_skoffset      = input.int(26,                               'Senkou-Span Offset',                        minval=1,             group=gichi)
I_skvolsetup    = input.bool(true,                            'Volume',                                                          group=gichi, inline='sn_chks')
I_atrsetup      = input.bool(true,                            'Volatility',                                                      group=gichi, inline='sn_chks')
I_skchfilter    = input.bool(true,                            'Chikou Trend Filter',                                             group=gichi, inline='sn_chks')
I_kumofill      = input.bool(true,                            'Kumo Fill',                                                       group=gichi, inline='kumo')
I_kumofillt     = input.int(65,                               'Transparency',                              minval=1,             group=gichi, inline='kumo')
I_volsetup      = input.bool(true,                            'Volume?',                                                         group=gadvset)
I_tkkjcross     = input.bool(true,                            'Tenkan-Sen/Kijun-Sen Cross?',                                     group=gadvset)
I_atrvolatility = input.bool(true,                            'Volatility?',                                                     group=gadvset)
I_tkeqkj        = input.bool(true,                            'Tenkan-Sen Equal Kijun-Sen?',                                     group=gadvset)
I_chgtp         = input.bool(true,                            'Chikou Greater Than Price?',                                      group=gadvset)
I_chmom         = input.bool(true,                            'Chikou Momentum?',                                                group=gadvset)
I_pgtk          = input.bool(true,                            'Price Greater Than Kumo?',                                        group=gadvset)
I_pgttk         = input.bool(true,                            'Price Greater Than Tenkan-Sen?',                                  group=gadvset)
I_pgtchf        = input.bool(true,                            'Chikou Trend Filter?',                                            group=gadvset)
I_volosctype    = input.string('On Balance Volume',           'Volume Oscillator Type',                    options=['TFS Volume Oscillator', 'On Balance Volume', 'Klinger Volume Oscillator', 'Cumulative Volume Oscillator', 'Volume Zone Oscillator'], group=gvosc)
I_volosctypetk  = input.string('On Balance Volume',           'Volume Oscillator Type for Tenkan-Sen',     options=['TFS Volume Oscillator', 'On Balance Volume', 'Klinger Volume Oscillator', 'Cumulative Volume Oscillator', 'Volume Zone Oscillator'], group=gvosc)
I_volosctypekj  = input.string('On Balance Volume',           'Volume Oscillator Type for Kijun-Sen',      options=['TFS Volume Oscillator', 'On Balance Volume', 'Klinger Volume Oscillator', 'Cumulative Volume Oscillator', 'Volume Zone Oscillator'], group=gvosc)
I_volosctypesk  = input.string('On Balance Volume',           'Volume Oscillator Type for Senkou',         options=['TFS Volume Oscillator', 'On Balance Volume', 'Klinger Volume Oscillator', 'Cumulative Volume Oscillator', 'Volume Zone Oscillator'], group=gvosc)
I_volosctypech  = input.string('On Balance Volume',           'Volume Oscillator Type for Chikou',         options=['TFS Volume Oscillator', 'On Balance Volume', 'Klinger Volume Oscillator', 'Cumulative Volume Oscillator', 'Volume Zone Oscillator'], group=gvosc)
I_volumelen     = input.int(30,                               'Volume Length',                             minval=1,             group=gvosc)
I_volzonelen    = input.int(21,                               'Volume Zone Length',                        minval=1,             group=gvosc)
I_volfastlen    = input.int(34,                               'Volume Fast Length',                        minval=1,             group=gvosc)
I_volslowlen    = input.int(55,                               'Volume Slow Length',                        minval=1,             group=gvosc)
I_rvolumetype   = input.string(pvtstr,                        'Relative Volume Strength Index Type',       options=[obvstr, cvdstr, pvtstr], group=gvrindex)
I_rvolumelen    = input.int(14,                               'Relative Volume Strength Index Length',     minval=1,             group=gvrindex)
I_volpeak       = input.int(50,                               'Relative Volume Strength Index Peak',       minval=1,             group=gvrindex)
i_emalen1       = input.int(8,                                'EMA 1 Length',                              minval=1,             group=gvrindex)
i_emalen2       = input.int(21,                               'EMA 2 Length',                              minval=1,             group=gvrindex)
i_atrfastlen    = input.int(14,                               'Average True Range Fast Length',                                  group=gatr)
i_atrslowlen    = input.int(46,                               'Average True Range Slow Length',                                  group=gatr)
i_showsr        = input.bool(true,                            'Show Supports/Resistances?',                                      group=gsr)
i_rescol        = input.color(color.new(color.red,   0),    'Resistance Color',                                                group=gsr,     inline='srcol')
i_supcol        = input.color(color.new(color.green, 0),    'Support Color',                                                   group=gsr,     inline='srcol')
i_maxline       = input.int(2,                                'Maximum Lines',                             minval=1, maxval=500, group=gsr,     inline='lines')
i_layout        = input.string('Wick',                        'Lines Type',                                options=['Wick', 'Zone'], group=gsr, inline='lines')
i_linewidth     = input.int(1,                                'Lines Width',                          minval=1, maxval=3,   group=gsr,     inline='lines style')
i_linestyle     = input.string('Solid',                       'Lines Style',                               options=['Solid', 'Dotted', 'Dashed'], group=gsr, inline='lines style')
i_extend        = input.bool(true,                            'Extend Lines',                                                    group=gsr,     inline='lines style')
i_psylevels     = input(false,                                'Display Psychological Levels?',                                   group=gpsylvl)
i_linescounter  = input(4,                                    'Lines Above/Below',                                               group=gpsylvl)
i_psylinescol   = input.color(color.new(color.gray,  0),    'Lines Color',                                                     group=gpsylvl)
i_showbc        = input.bool(true,                            'Use Bar Color?',                                                  group=gbarcol)
i_bearbarcol    = input.color(color.new(#910000,     0),    'Bear',                                                            group=gbarcol, inline='barcolor')
i_bullbarcol    = input.color(color.new(#006400,     0),    'Bull',                                                            group=gbarcol, inline='barcolor')
i_consobarcol   = input.color(color.new(#FF9800,     0),    'Consolidation',                                                   group=gbarcol, inline='barcolor')
i_neutralbarcol = input.color(color.new(#000000,   100),    'Neutral',                                                         group=gbarcol, inline='barcolor')
i_showtable     = input(true,                                 'Show Panel?',                                                     group=gtable)
i_tablepresets  = input.string('Custom',                      'Presets',                                   options=['Custom', '9/26/52/26     - 6D Markets (Default)', '8/22/44/22     - 5D Markets', '9/30/60/30     - 24h/7D Markets (Crypto)', '20/60/120/60   - 24h/7D Markets (Slow Version)'], group=gtable)
i_tableloc      = input.string('Bottom Right',                'Position',                                  options=['Bottom Right', 'Top Right', 'Bottom Left', 'Top Left', 'Top', 'Right', 'Bottom', 'Left'], group=gtable)
i_tabletxtsize  = input.string('Small',                       'Text Size',                                 options=['Tiny', 'Small', 'Normal', 'Large'], group=gtable)
i_tabletxtcol   = input.color(color.new(color.white, 0),    'Text Color',                                                      group=gtable)
i_tablebgcol    = input.color(color.new(#696969,    80),    'Background Color',                                                group=gtable)
i_tabletkpc     = input.bool(true,                            'Display Tenkan-Sen Price Cross?',                                 group=gtable)
i_tablekjpc     = input.bool(true,                            'Display Kijun-Sen Price Cross?',                                  group=gtable)
i_tablechpc     = input.bool(true,                            'Display Chikou Span Price Cross?',                                group=gtable)
i_tablekumobr   = input.bool(true,                            'Display Kumo Breakout?',                                          group=gtable)
i_tablekumotw   = input.bool(true,                            'Display Kumo Twist?',                                             group=gtable)

//?--- Volume Heikin Ashi Calculation ---?

//Constant Price Variables

haclose = i_uha ? ohlc4 : close
vol     = volume

//Heikin Ashi Function

f_openha() =>
    haopen  = float(na)
    haopen := na(haopen[1]) ? (open + close) / 2 : (nz(haopen[1]) + nz(haclose[1])) / 2
    haopen

//Conditions

haopen    = i_uha ? f_openha() : open
haboolean = f_openha()

//?--- Price Variables Declaration ---?

open_      = open
high_      = high
low_       = low
close_     = close
bar_index_ = bar_index

//Alternative Price Variables Declaration

alternativesrc = i_altsrc == '(open + close +3 * (high + low)) / 8'      ? (open + close +3 * (high  + low)) / 8             :
     i_altsrc             == 'close + high + low -2 * open'              ? close + high + low -2 * open                      :
     i_altsrc             == '(close +5 * (high + low) -7 * (open)) / 4' ? (close        +5 * (high  + low) -7 * (open)) / 4 :
     i_altsrc             == '(open + close +5 * (high + low)) / 12'     ? (open + close +5 * (high  + low)) / 12            :
     i_altsrc             == '(close > open ? high : low)'               ? (close > open      ? high : low)                  :
     i_altsrc             == 'Heiken-Ashi'                               ? (ohlc4 > haboolean ? high : low)                  :
     i_src

altsrcres = i_wmas ? ta.swma(alternativesrc) : alternativesrc

//?--- Global Functions ---?

//Color Call Function

fzonecolor(srcolor, _call) =>
    c1 = color.r(srcolor)
    c2 = color.g(srcolor)
    c3 = color.b(srcolor)
    color.rgb(c1, c2, c3, _call)

//Lines Styles String Function

f_i_linestyle(_style) =>
    _style == 'Solid' ? line.style_solid : _style == 'Dotted' ? line.style_dotted : line.style_dashed

//Volume Oscillator Functions

f_patternrate(cond, tw, bw, body) =>
    ret  = 0.5 * (tw + bw + (cond ? 2 * body : 0)) / (tw + bw + body)
    ret := nz(ret) == 0 ? 0.5 : ret
    ret

f_volcalc(vol_src, _open, _high, _low, _close) =>
    float result = 0
    tw           = _high - math.max(_open, _close)
    bw           = math.min(_open,  _close) - _low
    body         = math.abs(_close - _open)
    deltaup      = vol_src * f_patternrate(_open <= _close, tw, bw, body)
    deltadown    = vol_src * f_patternrate(_open  > _close, tw, bw, body)
    delta        = _close >= _open ? deltaup : -deltadown
    cumdelta     = ta.cum(delta)
    float ctl    = na
    ctl         := cumdelta
    cv           = I_rvolumetype == obvstr ? ta.obv : I_rvolumetype == cvdstr ? ctl : ta.pvt
    ema1         = ta.ema(cv, i_emalen1)
    ema2         = ta.ema(cv, i_emalen2)
    result      := ema1 - ema2
    result

f_zone(_src, _type, _len) =>
    vp = _src > _src[1] ? _type : _src < _src[1] ? -_type : _src == _src[1] ? 0 : 0
    z  = 100 * (ta.ema(vp, _len) / ta.ema(_type, _len))
    z

f_volzosc(vol_src, _close) =>
    float result = 0
    zLen         = I_volzonelen
    result      := f_zone(_close, vol_src, zLen)
    result

f_volosc(type, vol_src, vol_len, _open, _high, _low, _close) =>
    float result = 0
    if type == 'TFS Volume Oscillator'
        iff_1    = _close < _open ? -vol_src : 0
        naccvol  = math.sum(_close > _open ? vol_src : iff_1, vol_len)
        result  := naccvol / vol_len
        result
    if type == 'On Balance Volume'
        result  := ta.cum(math.sign(ta.change(_close)) * vol_src)
        result
    if type == 'Klinger Volume Oscillator'
        fastx    = I_volfastlen
        slowx    = I_volslowlen
        xtrend   = _close > _close[1] ? vol * 100 : -vol * 100
        xfast    = ta.ema(xtrend, fastx)
        xslow    = ta.ema(xtrend, slowx)
        result  := xfast - xslow
        result
    if type == 'Cumulative Volume Oscillator'
        result  := f_volcalc(vol_src, _open, _high, _low, _close)
        result
    if type == 'Volume Zone Oscillator'
        result  := f_volzosc(vol_src, _close)
        result
    result

//Kijun V2 Function

f_kjv2(src, len) =>
    var float result = 0.0
    kijun            = math.avg(ta.lowest(len), ta.highest(len))
    conversionLine   = math.avg(ta.lowest(len   / i_kjdivider), ta.highest(len / i_kjdivider))
    delta            = (kijun + conversionLine) / 2
    result          := delta
    result

//?--- Relative Volume Strength Index calculation ---?

tksignal  = f_volosc(I_volosctypetk, vol, I_rvolumelen, haopen, high, low, haclose)
kjsignal  = f_volosc(I_volosctypekj, vol, I_rvolumelen, haopen, high, low, haclose)
sksignal  = f_volosc(I_volosctypesk, vol, I_rvolumelen, haopen, high, low, haclose)
chsignal  = f_volosc(I_volosctypech, vol, I_rvolumelen, haopen, high, low, haclose)
sumsignal = f_volosc(I_volosctype,   vol, I_rvolumelen, haopen, high, low, haclose)

//?--- Volume Breakout Calculation ---?

tkbrvoldn = tksignal < I_volpeak
tkbrvolup = tksignal > I_volpeak
kjbrvoldn = kjsignal < I_volpeak
kjbrvolup = kjsignal > I_volpeak
skbrvoldn = sksignal < I_volpeak
skbrvolup = sksignal > I_volpeak
chbrvoldn = chsignal < I_volpeak
chbrvolup = chsignal > I_volpeak

//Conditions

signalbrvoldn = sumsignal < I_volpeak
signalbrvolup = sumsignal > I_volpeak

//?--- Volatility Strength ---?

atrvolmeter = ta.atr(i_atrfastlen) > ta.atr(i_atrslowlen)

//Adaptive Chikou Function

f_chikou(float src, simple int len, float _high, float _low, color bull_col, color bear_col, color r_col) =>
    var isup       = bool(na)
    var isdown     = bool(na)
    var _re        = bool(na)
    var sig        = int(na)
    var color _clr = color.new(na, 0)
    isup          := src > ta.highest(_high, len)[len]
    isdown        := src < ta.lowest(_low,   len)[len]
    _re           := src < ta.highest(_high, len)[len] and src > ta.lowest(_low, len)[len]
    _clr          := isdown ? bear_col : isup ? bull_col : r_col
    sig           := isup ? 1 : isdown ? -1 : 0
    [_clr, sig]

[chikou_clr, chikoufiltersig] = f_chikou(altsrcres, i_chfiltper, high, low, i_chbullcol, i_chbearcol, i_chconsocol)

//Arrays Index Functions

f_boolean(chka, reference_a) =>
	var result_bool      = bool(na)
    for i                = 0 to array.size(chka) -1
        if array.get(chka, i) == true
            result_bool := array.get(reference_a, i)
            break

	for i = 0 to array.size(chka) -1
		result_bool := array.get(chka, i) ? array.get(reference_a, i) and result_bool : result_bool
	result_bool

//Boolean Calculation

bool[] tkarray    = array.from(i_tkvolsetup,
     i_tkatrsetup,
     i_tkchfilter)
bool[] kjarray    = array.from(i_kjvolsetup,
     i_kjatrsetup,
     i_kjchfilter)
bool[] skarray    = array.from(I_skvolsetup,
     I_atrsetup,
     I_skchfilter)
bool[] charray    = array.from(i_chvolsetup,
     i_chatrsetup,
     i_chtfilter)
bool[] tkvolarray = array.from(tkbrvolup,
     atrvolmeter,
     chikoufiltersig ==  1)
bool[] kjvolarray = array.from(kjbrvolup,
     atrvolmeter,
     chikoufiltersig ==  1)
bool[] skvolarray = array.from(skbrvolup,
     atrvolmeter,
     chikoufiltersig ==  1)
bool[] chvolarray = array.from(chbrvolup,
     atrvolmeter,
     chikoufiltersig ==  1)

//Boolean to Conditions

booltkup = f_boolean(tkarray, tkvolarray)
boolkjup = f_boolean(kjarray, kjvolarray)
boolchup = f_boolean(charray, chvolarray)
boolskup = f_boolean(skarray, skvolarray)

//Dynamic Length Function

f_dyn(bool para, float adapt_Pct, simple int minLength, simple int maxLength) =>
    var dyna_len    = int(na)
    var float i_len = math.avg(minLength, maxLength)
    i_len          := para ? math.max(minLength, i_len * adapt_Pct) : math.min(maxLength, i_len * (2-adapt_Pct))
    dyna_len       := int(i_len)
    dyna_len

//Dynamic Length Conditions

dyntk = f_dyn(booltkup,  i_tkdynperc, i_tkminlen, i_tkmaxlen)
dynkj = f_dyn(boolkjup , i_kjdynperc, i_kjminlen, i_kjmaxlen)
dynsk = f_dyn(boolskup , I_skperc,    I_skminlen, I_skmaxlen)
dynch = f_dyn(boolchup , i_chdynperc, i_chminlen, i_chmaxlen)

//?--- Index Calculation ---?

tenkansen  = f_kjv2(altsrcres,                                 dyntk)
kijunsen   = f_kjv2(altsrcres,                                 dynkj)
senkoua    = math.avg(tenkansen,                            kijunsen)
senkoub    = math.avg(ta.highest(high, dynsk), ta.lowest(low, dynsk))
chikouspan = altsrcres

//Tenkan-Sen/kijun-Sen Boolean Conditions to Float

var float tkbool = na
if tenkansen
    tkbool := tenkansen
    tkbool
var float kjbool = na
if kijunsen
    kjbool := kijunsen
    kjbool

//?--- Dynamic Type Calculation ---?

bearmomentum = ta.mom(altsrcres, dynch                              - 1) < 0
bullmomentum = ta.mom(altsrcres, dynch                              - 1) > 0
cloudhigh    = math.max(senkoua[I_skoffset - 1], senkoub[I_skoffset - 1])
cloudlow     = math.min(senkoua[I_skoffset - 1], senkoub[I_skoffset - 1])
pbk          = altsrcres < cloudhigh
pak          = altsrcres > cloudhigh

//Boolean Arrays Variables

bool[] indexarray = array.from(I_volsetup,
     I_atrvolatility,
     I_tkkjcross,
     I_chmom,
     I_chgtp,
     I_pgtk,
     I_pgttk,
     I_pgtchf)

bool[] downvolumearray  = array.from(signalbrvoldn,
     atrvolmeter,
     tenkansen  < kijunsen,
     bearmomentum,
     chikouspan < altsrcres[int(dynch)],
     pbk,
     altsrcres  < tenkansen,
     chikoufiltersig == -1)

bool[] uppervolumearray = array.from(signalbrvolup,
     atrvolmeter,
     tenkansen  > kijunsen,
     bullmomentum,
     chikouspan > altsrcres[int(dynch)],
     pak,
     tenkansen,
     chikoufiltersig ==  1)

//Conditions Calculation

bearfilterdn  = f_boolean(indexarray,  downvolumearray)
bullfilterup  = f_boolean(indexarray, uppervolumearray)
bearcondition = I_tkeqkj ? tenkansen == kijunsen and tenkansen[1] > kijunsen[1] or bearfilterdn : bearfilterdn
bullcondition = I_tkeqkj ? tenkansen == kijunsen and tenkansen[1] < kijunsen[1] or bullfilterup : bullfilterup
isdown        = bearcondition
isup          = bullcondition

//Conditions

sell = isdown and not isdown[1]
buy  = isup   and not   isup[1]

//Sig Calculation

var sig  =  0
if sell and sig >= 0
    sig := -1
if buy  and sig <= 0
    sig :=  1

//Sig Conditions

shortcr = sig == -1 and sig[1] != -1
longcr  = sig ==  1 and sig[1] !=  1

//Boolean Conditions to Float

var float ichibearprice = na
if shortcr
    ichibearprice := bar_index
    ichibearprice
var float ichibullprice = na
if longcr
    ichibullprice := bar_index
    ichibullprice

//Labels Calculation

if i_showlabels
    l = ta.change(ichibearprice) ? label.new(bar_index, ichibearprice[1] + 0.01, str.tostring(math.round_to_mintick(high)), color=color.new(color.black, 0), textcolor=color.new(color.white, 0), style=label.style_label_down, yloc=yloc.abovebar, size=size.small) : ta.change(ichibullprice) ? label.new(bar_index, ichibullprice[1] - 0.01, str.tostring(math.round_to_mintick(low)), color=color.new(color.black, 0), textcolor=color.new(color.white, 0), style=label.style_label_up, yloc=yloc.belowbar, size=size.small) : na
    l

//Volatility Coordination Constant Variable

atrxy = 0.85 * ta.atr(5)

//?--- Plotting ---?

plotshape(i_showlabels and shortcr ? (high) + atrxy : na, style=shape.triangledown, color=i_rescol, location=location.absolute, size=size.small)
plotshape(i_showlabels and longcr  ? (low)  - atrxy : na, style=shape.triangleup,   color=i_supcol, location=location.absolute, size=size.small)
plotshape(i_showlabels and sell    ? high   + atrxy : na, style=shape.circle,       color=i_rescol, location=location.absolute,  size=size.tiny)
plotshape(i_showlabels and buy     ? low    - atrxy : na, style=shape.circle,       color=i_supcol, location=location.absolute,  size=size.tiny)

//plotchikouspan = plot(chikouspan, title='Chikou', color=not i_showchikou ? na : chikou_clr, linewidth=1, offset=-dynch)

f_colorgradient(_source, _min, _max, _cbear, _cbull) =>
    var float _center = _min + (_max - _min) / 2
    color     _return = _source >= _center ?
      color.from_gradient(_source, _min,    _center, color.new(_cbear,   0), color.new(_cbear, 100)) :
      color.from_gradient(_source, _center, _max,    color.new(_cbull, 100), color.new(_cbull,   0))

skclr  = (senkoua - senkoub) / altsrcres * 100
skfill = senkoua > senkoub ? color.from_gradient(ta.rsi(math.avg(senkoua , senkoub), 14) , 0, 100, I_skconso, I_skbull) :
     senkoua     < senkoub ? color.from_gradient(ta.rsi(math.avg(senkoua , senkoub), 14) , 0, 100, I_skconso, I_skbear) : I_skconso

plottenkansen = plot(tenkansen, title='Tenkan-Sen',    color=not i_showtenkan ? na : i_tenkancolor, linewidth=1,            offset=0)
plotkijunsen  = plot(kijunsen,  title='Kijun-Sen',     color=not i_showkijun  ? na : i_kijuncolor,  linewidth=1,            offset=0)
plotsenkoua   = plot(senkoua,   title='Senkou-Span A', color=not I_ska        ? na : I_skbull,      linewidth=1, offset=I_skoffset-1)
plotsenkoub   = plot(senkoub,   title='Senkou-Span B', color=not I_skb        ? na : I_skbear,      linewidth=1, offset=I_skoffset-1)
fill(plotsenkoua, plotsenkoub,  color=not I_kumofill ? na : color.new(skfill, I_kumofillt))

//Tenkan-Sen/kijun-Sen Price Plotting

if i_showtenkan and i_showprice
    l1 = label.new(bar_index, tkbool, 'Tenkan-Sen - ' + str.tostring(math.round_to_mintick(tkbool)), color=color.new(i_tenkancolor, 100), textcolor=color.new(i_tenkancolor, 0), style=label.style_label_left, yloc=yloc.price, size=size.small)
    l1
    label.delete(l1[1])
if i_showkijun  and i_showprice
    l1 = label.new(bar_index, kjbool, 'Kijun-Sen - '  + str.tostring(math.round_to_mintick(kjbool)), color=color.new(i_kijuncolor,  100), textcolor=color.new(i_kijuncolor,  0), style=label.style_label_left, yloc=yloc.price, size=size.small)
    l1
    label.delete(l1[1])

//Bar Color Plotting

colbar(src, tenkansen, kijunsen) =>
    vbarcolor  = color.new(na, 0)
    vbarcolor := src > tenkansen and src > kijunsen?  i_bullbarcol :
         src < tenkansen and src < kijunsen ? i_bearbarcol         :
         src > tenkansen and src < kijunsen ? i_consobarcol        :
         src < tenkansen and src > kijunsen ? i_neutralbarcol      : na
    vbarcolor

bc = colbar(close, tenkansen, kijunsen)

barcolor(i_showbc ? bc : na)

//?--- Kijun-Sen Hidden Supports/Resistances ---?

//Smoothed MA Calculation

smma1  = 0.0
smma2  = 0.0
smakj1 = ta.sma(close, i_kjminlen)
smakj2 = ta.sma(close, i_kjmaxlen)
smma1 := na(smma1[1]) ? smakj1 : (smma1[1] * (20 - 1) + close) / 20
smma2 := na(smma2[1]) ? smakj2 : (smma2[1] * (60 - 1) + close) / 60

//Kijun-Sen Calculation

kjsmma = math.avg(ta.lowest(26), ta.highest(26))

//Conditions

hiddenbearkj = ta.crossunder(smma1, kjsmma) and kjsmma < smma2 and close < smma1
hiddenbullkj = ta.crossover(smma1,  kjsmma) and kjsmma > smma2 and close > smma1

//Boolean Conditions to Float

var float bearhkj = na
if hiddenbearkj
    bearhkj := high
    bearhkj
var float bullhkj = na
if hiddenbullkj
    bullhkj := low
    bullhkj

//Labels Calculation

if i_showkjhlabels
    l = ta.change(bearhkj) ? label.new(bar_index, bearhkj[1] + 0.01, str.tostring(math.round_to_mintick(bearhkj)), color=color.new(color.black, 0), textcolor=color.new(color.white, 0), style=label.style_label_down, yloc=yloc.abovebar, size=size.small) : ta.change(bullhkj) ? label.new(bar_index, bullhkj[1] - 0.01, str.tostring(math.round_to_mintick(bullhkj)), color=color.new(color.black, 0), textcolor=color.new(color.white, 0), style=label.style_label_up, yloc=yloc.belowbar, size=size.small) : na
    l

//Plotting

plotshape(i_showkjhlabels ? hiddenbearkj : na, title='Bearish Hidden Kijun-Sen', style=shape.triangledown, location=location.abovebar, color=i_rescol, size=size.tiny)
plotshape(i_showkjhlabels ? hiddenbullkj : na, title='Bullish Hidden Kijun-Sen', style=shape.triangleup,   location=location.belowbar, color=i_supcol, size=size.tiny)

//Hidden Kijun S/R Variables Declaration

var int     numberofline2       = i_maxline
var float   upperphzone2        = na
var float   upperplzone2        = na
var float   lowerphzone2        = na
var float   lowerplzone2        = na
var line[]  upperphzonearr2     = array.new_line(0, na)
var line[]  upperplzonearr2     = array.new_line(0, na)
var line[]  lowerphzonearr2     = array.new_line(0, na)
var line[]  lowerplzonearr2     = array.new_line(0, na)
var line    upperphzoneline2    = na
var line    upperplzoneline2    = na
var line    lowerphzoneline2    = na
var line    lowerplzoneline2    = na
var bool[]  upperzonetestedarr2 = array.new_bool(0, false)
var bool[]  lowerzonetestedarr2 = array.new_bool(0, false)
var bool    upperzonetested2    = false
var bool    lowerzonetested2    = false
var bool    nobool2             = true
var color   upperzonecolor2     = color.red
var color   lowerzonecolor2     = color.green
var label[] labelpharr2         = array.new_label(0, na)
var label[] labelplarr2         = array.new_label(0, na)
var label   labelph2            = na
var label   labelpl2            = na

//Hidden Kijun Resistances Calculation

if i_showsr and i_showkjhsr and hiddenbearkj
    upperphzone2     := high_
    upperplzone2     := close_ < open_     ? close_ : open_
    upperplzoneline2 := i_layout == 'Zone' ? line.new(bar_index_,  upperplzone2, bar_index, upperplzone2, width=i_linewidth) : na
    upperphzoneline2 := nobool2            ? line.new(bar_index_,  upperphzone2, bar_index, upperphzone2, width=i_linewidth) : line.new(bar_index_, (upperphzone2 + upperplzone2) / 2, bar_index, (upperphzone2 + upperplzone2) / 2, width=i_linewidth)
    labelph2         := i_showsr           ? label.new(bar_index_, nobool2 ? upperphzone2 : (upperphzone2 + upperplzone2) / 2, text=str.tostring(bar_index - bar_index_), textcolor=upperzonecolor2, style=label.style_none) : na
    if array.size(upperphzonearr2) > numberofline2
        line.delete(array.shift(upperphzonearr2))
        line.delete(array.shift(upperplzonearr2))
        array.shift(upperzonetestedarr2)
        label.delete(array.shift(labelpharr2))
    array.push(upperphzonearr2, upperphzoneline2)
    array.push(upperplzonearr2, upperplzoneline2)
    array.push(upperzonetestedarr2,       i_extend ? true : false)
    array.push(labelpharr2,             labelph2)
if array.size(upperplzonearr2) > 0
    for i = 0 to array.size(upperplzonearr2) - 1 by 1
        line  tempupperline2  = array.get(upperphzonearr2,     i)
        line  templowerline2  = array.get(upperplzonearr2,     i)
        label linepricelabel2 = array.get(labelpharr2,         i)
        bool  tested2         = array.get(upperzonetestedarr2, i)
        line.set_style(tempupperline2, f_i_linestyle(i_linestyle))
        line.set_style(templowerline2, f_i_linestyle(i_linestyle))
        line.set_color(tempupperline2, color.from_gradient(i,       1, numberofline2, fzonecolor(upperzonecolor2, 00), fzonecolor(upperzonecolor2, 00)))
        line.set_color(templowerline2, color.from_gradient(i,       1, numberofline2, fzonecolor(upperzonecolor2, 00), fzonecolor(upperzonecolor2, 00)))
        label.set_textcolor(linepricelabel2, color.from_gradient(i, 1, numberofline2, fzonecolor(upperzonecolor2, 00), upperzonecolor2))
        label.set_text(linepricelabel2, str.tostring(math.round_to_mintick(line.get_y1(tempupperline2))))
        label.set_text(linepricelabel2, 'Hidden Kijun Resistance - ' + str.tostring(math.round_to_mintick(line.get_y1(tempupperline2))))
        label.set_x(linepricelabel2, bar_index)
        crossed = high > line.get_y1(tempupperline2)
        if crossed and not tested2
            array.set(upperzonetestedarr2, i, true)
            label.delete(linepricelabel2)
        else if i_extend ? tested2 : not tested2
            line.set_x2(tempupperline2, bar_index)
            array.set(upperphzonearr2, i, tempupperline2)
            line.set_x2(templowerline2, bar_index)
            array.set(upperplzonearr2, i, templowerline2)

//Hidden Kijun Supports Calculation

if i_showsr and i_showkjhsr and hiddenbullkj
    lowerplzone2     := low_
    lowerphzone2     := close_ < open_     ? open_ : close_
    lowerphzoneline2 := i_layout == 'Zone' ? line.new(bar_index_,  lowerphzone2, bar_index, lowerphzone2, width=i_linewidth) : na
    lowerplzoneline2 := nobool2            ? line.new(bar_index_,  lowerplzone2, bar_index, lowerplzone2, width=i_linewidth) : line.new(bar_index_, (lowerphzone2 + lowerplzone2) / 2, bar_index, (lowerphzone2 + lowerplzone2) / 2, width=i_linewidth)
    labelpl2         := i_showsr           ? label.new(bar_index_, nobool2 ? lowerplzone2 : (lowerphzone2 + lowerplzone2) / 2, text=str.tostring(bar_index - bar_index_), textcolor=lowerzonecolor2, style=label.style_none) : na
    if array.size(lowerphzonearr2) > numberofline2
        line.delete(array.shift(lowerphzonearr2))
        line.delete(array.shift(lowerplzonearr2))
        array.shift(lowerzonetestedarr2)
        label.delete(array.shift(labelplarr2))
    array.push(lowerphzonearr2, lowerphzoneline2)
    array.push(lowerplzonearr2, lowerplzoneline2)
    array.push(lowerzonetestedarr2,       i_extend ? true : false)
    array.push(labelplarr2,             labelpl2)
if array.size(lowerplzonearr2) > 0
    for i = 0 to array.size(lowerplzonearr2) - 1 by 1
        line  tempupperline2  = array.get(lowerphzonearr2,     i)
        line  templowerline2  = array.get(lowerplzonearr2,     i)
        label linepricelabel2 = array.get(labelplarr2,         i)
        bool  tested2         = array.get(lowerzonetestedarr2, i)
        line.set_style(tempupperline2, f_i_linestyle(i_linestyle))
        line.set_style(templowerline2, f_i_linestyle(i_linestyle))
        line.set_color(tempupperline2, color.from_gradient(i,       1, numberofline2, fzonecolor(lowerzonecolor2, 00), fzonecolor(lowerzonecolor2, 00)))
        line.set_color(templowerline2, color.from_gradient(i,       1, numberofline2, fzonecolor(lowerzonecolor2, 00), fzonecolor(lowerzonecolor2, 00)))
        label.set_textcolor(linepricelabel2, color.from_gradient(i, 1, numberofline2, fzonecolor(lowerzonecolor2, 00), lowerzonecolor2))
        label.set_text(linepricelabel2, str.tostring(math.round_to_mintick(line.get_y1(templowerline2))))
        label.set_text(linepricelabel2, 'Hidden Kijun Support - ' + str.tostring(math.round_to_mintick(line.get_y1(templowerline2))))
        label.set_x(linepricelabel2, bar_index)
        crossed = low < line.get_y1(templowerline2)
        if crossed and not tested2
            array.set(lowerzonetestedarr2, i, true)
            label.delete(linepricelabel2)
        else if i_extend ? tested2 : not tested2
            line.set_x2(tempupperline2, bar_index)
            array.set(lowerphzonearr2, i, tempupperline2)
            line.set_x2(templowerline2, bar_index)
            array.set(lowerplzonearr2, i, templowerline2)

//?--- Table Calculation ---?

//Constant Colors Variables

itablestrongbearcol  = color.new(color.red,    0)
itablebearcol        = color.new(color.maroon, 0)
itableneutralbearcol = color.new(color.silver, 0)
itablestrongbullcol  = color.new(color.lime,   0)
itablebullcol        = color.new(color.green,  0)
itableneutralbullcol = color.new(color.silver, 0)
itableconsocol       = color.new(color.orange, 0)

//Boolean Dynamic Settings To Integer Conditions

var int dyntkint = 0
if dyntk
    dyntkint := dyntk
    dyntkint

var int dynkjint = 0
if dynkj
    dynkjint := dynkj
    dynkjint

var int dynskint = 0
if dynsk
    dynskint := dynsk
    dynskint

var int dynchint = 0
if dynch
    dynchint := dynch
    dynchint

//Global Functions

donchian(len) =>
    math.avg(ta.lowest(len), ta.highest(len))

f_presets(p) =>
    if p == 'Custom'
        [dyntkint, dynkjint, dynskint, dynch]
    else if p == '9/26/52/26     - 6D Markets (Default)'
        [9, 26, 52, 26]
    else if p == '8/22/44/22     - 5D Markets'
        [8, 22, 44, 22]
    else if p == '9/30/60/30     - 24h/7D Markets (Crypto)'
        [10, 30, 60, 30]
    else if p == '20/60/120/60   - 24h/7D Markets (Slow Version)'
        [20, 60, 120, 60]
    else
        [0, 0, 0, 0]

f_tablestringpos(p) =>
    p == 'Bottom Right' ? position.bottom_right : p == 'Top Right' ? position.top_right : p == 'Bottom Left' ? position.bottom_left : p == 'Top Left' ? position.top_left : p == 'Top' ? position.top_center : p == 'Right' ? position.middle_right : p == 'Bottom' ? position.bottom_center : p == 'Left' ? position.middle_left : na

f_tablestringdirsym(trend) =>
    trend == 1 ? '? Strong' : trend == 2 ? '? Neutral' : trend == 3 ? '? Weak' : trend == -1 ? '? Strong' : trend == -2 ? '? Neutral' : trend == -3 ? '? Weak' : ' Consolidation'

f_tablestringcolor(trend, c_up, c_down, c_consolidation) =>
    trend > 0 ? c_up : trend < 0 ? c_down : c_consolidation

f_tablestringcolordir(trend, c_up, c_down) =>
    trend > 0 ? c_up : c_down

f_tablecloudtrend(l1, l2) =>
    l1 > l2 ? 1 : -1

f_tabletrendsum(sum, count) =>
    sum == count ? 1 : sum == -count ? -1 : 0

f_tablestrengthconditions(pos, uptrend) =>
    uptrend ? pos == 1 ? 1 : pos == 0 ? 2 : 3 : pos == -1 ? -1 : pos == 0 ? -2 : -3

//Presets Calculation

[i_conversion_len, i_base_len, i_lagging_len, i_offset] = f_presets(i_tablepresets)

//Presets Conditions

i_conversion = donchian(i_conversion_len)
i_base       = donchian(i_base_len)
i_lead1      = math.avg(i_conversion, i_base)
i_lead2      = donchian(i_lagging_len)
i_cloud_top2 = math.max(i_lead1,     i_lead2)
i_cloud_bot2 = math.min(i_lead1,     i_lead2)

//Constant Array Variable

tablearrindex = array.new_int(0)

//Signals Conditions Function

f_tableconditions(enabled, signal) =>
    if enabled
        array.push(tablearrindex, signal)

//Calculation

i_lead1_current         = i_lead1[i_offset - 1]
i_lead2_current         = i_lead2[i_offset - 1]
i_cloud_top             = math.max(i_lead1_current, i_lead2_current)
i_cloud_bot             = math.min(i_lead1_current, i_lead2_current)
table_base_position     = i_base > i_cloud_top ? 1 : i_base < i_cloud_bot ? -1 : 0
table_base_breakout     = close > i_base                 ? f_tablestrengthconditions(table_base_position,    true) : f_tablestrengthconditions(table_base_position,   false)
table_cloud2_trend      = f_tablecloudtrend(i_conversion, i_base)
table_cloud2_top        = math.max(i_base, i_conversion)
table_cloud2_bot        = math.min(i_base, i_conversion)
table_cloud2_position   = table_cloud2_bot > i_cloud_top ? 1 : table_cloud2_top < i_cloud_bot ? -1 : 0
table_cloud2_cross      = table_cloud2_trend  == 1       ? f_tablestrengthconditions(table_cloud2_position,  true) : f_tablestrengthconditions(table_cloud2_position, false)
table_lagging_lead1     = i_lead1_current[i_offset - 1]
table_lagging_lead2     = i_lead2_current[i_offset - 1]
table_lagging_cloud_top = math.max(table_lagging_lead1, table_lagging_lead2)
table_lagging_cloud_bot = math.min(table_lagging_lead1, table_lagging_lead2)
table_lagging_high      = high[i_offset - 1]
table_lagging_low       = low[i_offset  - 1]
table_lagging_trend     = close > table_lagging_high     ? 1 : close < table_lagging_low ? -1 : 0
table_lagging_position  = close > i_cloud_top            ? 1 : close < i_cloud_bot       ? -1 : 0
table_lagging_cross     = table_lagging_trend == 1       ? f_tablestrengthconditions(table_lagging_position, true) : table_lagging_trend == -1 ? f_tablestrengthconditions(table_lagging_position, false) : 0
table_cloud_breakout    = close > i_cloud_top            ? 1 : close < i_cloud_bot       ? -1 : 0
table_cloud_trend       = f_tablecloudtrend(i_lead1, i_lead2)
table_lead_cross        = table_cloud_trend   == 1       ? f_tablestrengthconditions(table_cloud_breakout,   true) :                               f_tablestrengthconditions(table_cloud_breakout, false)

//Conditions Functions

f_tableconditions(i_tablekjpc,    table_base_breakout)
f_tableconditions(i_tabletkpc,     table_cloud2_cross)
f_tableconditions(i_tablechpc,    table_lagging_cross)
f_tableconditions(i_tablekumobr, table_cloud_breakout)
f_tableconditions(i_tablekumotw,     table_lead_cross)

//Conditions

table_signal_max              = array.max(tablearrindex)
table_signal_min              = array.min(tablearrindex)
table_signal                  = table_signal_min > 0 ? table_signal_max : table_signal_max < 0 ? table_signal_min : 0
table_changed                 = table_signal != table_signal[1]
table_downtrend               = table_changed       and table_signal    == -1
table_uptrend                 = table_changed       and table_signal    ==  1
table_consolidation           = table_changed       and table_signal    ==  0
table_consolidation_downtrend = table_consolidation and table_signal[1] == -1
table_consolidation_uptrend   = table_consolidation and table_signal[1] ==  1

//Colors String Function

f_tablecolors(t) =>
    t == 1 ? itablestrongbullcol : t == 2 ? itableneutralbullcol : t == 3 ? itablebullcol : t == -1 ? itablestrongbearcol : t == -2 ? itableneutralbearcol : t == -3 ? itablebearcol : itableconsocol

//String to Variable

i_panel_c_signal_text = f_tablecolors(table_signal)

//Table Text Size String Function

tabletxtwi = i_tabletxtsize == 'Tiny' ? size.tiny : i_tabletxtsize == 'Small' ? size.small : i_tabletxtsize == 'Normal' ? size.normal : i_tabletxtsize == 'Large' ? size.large : size.normal

//Plotting

var table i_panel = na
insertRow(i, text_1, trend, col) =>
    table.cell(i_panel, 0, i, text_1,                     text_color=col,                  text_halign=text.align_right, text_size=tabletxtwi)
    table.cell(i_panel, 1, i, f_tablestringdirsym(trend), text_color=f_tablecolors(trend), text_halign=text.align_left,  text_size=tabletxtwi)
    i + 1

if i_showtable and array.size(tablearrindex) > 0
    i_panel := table.new(position=f_tablestringpos(i_tableloc), columns=2, rows=20, bgcolor=i_tablebgcol, border_width=0)
    i = 0

    if i_tabletkpc
        i := insertRow(i, 'Tenkan-Sen Price Cross',  table_cloud2_cross,   i_tabletxtcol)
        i

    if i_tablekjpc
        i := insertRow(i, 'Kijun-Sen Price Cross',   table_base_breakout,  i_tabletxtcol)
        i

    if i_tablechpc
        i := insertRow(i, 'Chikou Span Price Cross', table_lagging_cross,  i_tabletxtcol)
        i

    if i_tablekumobr
        i := insertRow(i, 'Kumo Breakout',           table_cloud_breakout, i_tabletxtcol)
        i

    if i_tablekumotw
        i := insertRow(i, 'Kumo Twist',              table_lead_cross,     i_tabletxtcol)
        i

    table.cell(i_panel, 0, i, 'Status',                          bgcolor=i_tablebgcol, text_color=i_panel_c_signal_text, text_halign=text.align_right, text_size=tabletxtwi)
    table.cell(i_panel, 1, i, f_tablestringdirsym(table_signal), bgcolor=i_tablebgcol, text_color=i_panel_c_signal_text, text_halign=text.align_left,  text_size=tabletxtwi)

//?--- Support/Resistance Lines Variables Declaration ---?

var int     numberofline       = i_maxline
var float   upperphzone        = na
var float   upperplzone        = na
var float   lowerphzone        = na
var float   lowerplzone        = na
var line[]  upperphzonearr     = array.new_line(0, na)
var line[]  upperplzonearr     = array.new_line(0, na)
var line[]  lowerphzonearr     = array.new_line(0, na)
var line[]  lowerplzonearr     = array.new_line(0, na)
var line    upperphzoneline    = na
var line    upperplzoneline    = na
var line    lowerphzoneline    = na
var line    lowerplzoneline    = na
var bool[]  upperzonetestedarr = array.new_bool(0, false)
var bool[]  lowerzonetestedarr = array.new_bool(0, false)
var bool    upperzonetested    = false
var bool    lowerzonetested    = false
var bool    nobool             = true
var bool    showprice          = true
var color   upperzonecolor     = i_rescol
var color   lowerzonecolor     = i_supcol
var label[] labelpharr         = array.new_label(0, na)
var label[] labelplarr         = array.new_label(0, na)
var label   labelph            = na
var label   labelpl            = na

//Resistance Lines Calculation

if i_showsr and shortcr
    upperphzone     := high_
    upperplzone     := close_ < open_     ? close_ : open_
    upperplzoneline := i_layout == 'Zone' ? line.new(bar_index_,  upperplzone, bar_index, upperplzone, width=i_linewidth) : na
    upperphzoneline := nobool             ? line.new(bar_index_,  upperphzone, bar_index, upperphzone, width=i_linewidth) : line.new(bar_index_, (upperphzone + upperplzone) / 2, bar_index, (upperphzone + upperplzone) / 2, width=i_linewidth)
    labelph         := showprice          ? label.new(bar_index_, nobool ? upperphzone : (upperphzone + upperplzone) / 2, text=str.tostring(math.round_to_mintick(bar_index - bar_index_)), textcolor=upperzonecolor, style=label.style_none) : na
    if array.size(upperphzonearr) > numberofline
        line.delete(array.shift(upperphzonearr))
        line.delete(array.shift(upperplzonearr))
        array.shift(upperzonetestedarr)
        label.delete(array.shift(labelpharr))
    array.push(upperphzonearr, upperphzoneline)
    array.push(upperplzonearr, upperplzoneline)
    array.push(upperzonetestedarr,       i_extend ? true : false)
    array.push(labelpharr,             labelph)
if array.size(upperplzonearr) > 0
    for i = 0 to array.size(upperplzonearr) - 1 by 1
        line  tempupperline  = array.get(upperphzonearr,     i)
        line  templowerline  = array.get(upperplzonearr,     i)
        label linepricelabel = array.get(labelpharr,         i)
        bool  tested         = array.get(upperzonetestedarr, i)
        line.set_style(tempupperline, f_i_linestyle(i_linestyle))
        line.set_style(templowerline, f_i_linestyle(i_linestyle))
        line.set_color(tempupperline, color.from_gradient(i,       1, numberofline, fzonecolor(upperzonecolor, 00), fzonecolor(upperzonecolor, 00)))
        line.set_color(templowerline, color.from_gradient(i,       1, numberofline, fzonecolor(upperzonecolor, 00), fzonecolor(upperzonecolor, 00)))
        label.set_textcolor(linepricelabel, color.from_gradient(i, 1, numberofline, fzonecolor(upperzonecolor, 00), upperzonecolor))
        label.set_text(linepricelabel, str.tostring(math.round_to_mintick(line.get_y1(tempupperline))))
        label.set_text(linepricelabel, 'Resistance - ' + str.tostring(math.round_to_mintick(line.get_y1(tempupperline))))
        label.set_x(linepricelabel, bar_index)
        crossed = high > line.get_y1(tempupperline)
        if crossed and not tested
            array.set(upperzonetestedarr, i,  true)
            label.delete(linepricelabel)
        else if i_extend ? tested : not tested
            line.set_x2(tempupperline, bar_index)
            array.set(upperphzonearr, i, tempupperline)
            line.set_x2(templowerline, bar_index)
            array.set(upperplzonearr, i, templowerline)

//Support Lines Calculation

if i_showsr and longcr
    lowerplzone     := low_
    lowerphzone     := close_ < open_     ? open_ : close_
    lowerphzoneline := i_layout == 'Zone' ? line.new(bar_index_,  lowerphzone, bar_index, lowerphzone, width=i_linewidth) : na
    lowerplzoneline := nobool             ? line.new(bar_index_,  lowerplzone, bar_index, lowerplzone, width=i_linewidth) : line.new(bar_index_, (lowerphzone + lowerplzone) / 2, bar_index, (lowerphzone + lowerplzone) / 2, width=i_linewidth)
    labelpl         := showprice          ? label.new(bar_index_, nobool ? lowerplzone : (lowerphzone + lowerplzone) / 2, text=str.tostring(math.round_to_mintick(bar_index - bar_index_)), textcolor=lowerzonecolor, style=label.style_none) : na
    if array.size(lowerphzonearr) > numberofline
        line.delete(array.shift(lowerphzonearr))
        line.delete(array.shift(lowerplzonearr))
        array.shift(lowerzonetestedarr)
        label.delete(array.shift(labelplarr))
    array.push(lowerphzonearr, lowerphzoneline)
    array.push(lowerplzonearr, lowerplzoneline)
    array.push(lowerzonetestedarr,       i_extend ? true : false)
    array.push(labelplarr,             labelpl)
if array.size(lowerplzonearr) > 0
    for i = 0 to array.size(lowerplzonearr) - 1 by 1
        line  tempupperline  = array.get(lowerphzonearr,     i)
        line  templowerline  = array.get(lowerplzonearr,     i)
        label linepricelabel = array.get(labelplarr,         i)
        bool  tested         = array.get(lowerzonetestedarr, i)
        line.set_style(tempupperline, f_i_linestyle(i_linestyle))
        line.set_style(templowerline, f_i_linestyle(i_linestyle))
        line.set_color(tempupperline, color.from_gradient(i,       1, numberofline, fzonecolor(lowerzonecolor, 00), fzonecolor(lowerzonecolor, 00)))
        line.set_color(templowerline, color.from_gradient(i,       1, numberofline, fzonecolor(lowerzonecolor, 00), fzonecolor(lowerzonecolor, 00)))
        label.set_textcolor(linepricelabel, color.from_gradient(i, 1, numberofline, fzonecolor(lowerzonecolor, 00), lowerzonecolor))
        label.set_text(linepricelabel, str.tostring(math.round_to_mintick(line.get_y1(templowerline))))
        label.set_text(linepricelabel, 'Support - ' + str.tostring(math.round_to_mintick(line.get_y1(templowerline))))
        label.set_x(linepricelabel, bar_index)
        crossed = low < line.get_y1(templowerline)
        if crossed and not tested
            array.set(lowerzonetestedarr, i, true)
            label.delete(linepricelabel)
        else if i_extend ? tested : not tested
            line.set_x2(tempupperline, bar_index)
            array.set(lowerphzonearr, i, tempupperline)
            line.set_x2(templowerline, bar_index)
            array.set(lowerplzonearr, i, templowerline)

//?--- Psychological Levels ---?

//Constant Variable

var incr = syminfo.type == 'cfd' ? syminfo.mintick * 5000 : syminfo.type == 'crypto' ? syminfo.mintick * 5000 : syminfo.mintick * 500

//Calculation

if i_psylevels and barstate.islast
    for counter  = 0 to i_linescounter - 1 by 1
        incrup   = math.ceil(close  / incr) * incr + counter * incr
        incrdown = math.floor(close / incr) * incr - counter * incr

//Plotting

        line.new(bar_index, incrup,   bar_index - 1, incrup,   xloc=xloc.bar_index, extend=extend.both, color=i_psylinescol, width=1, style=line.style_solid)
        line.new(bar_index, incrdown, bar_index - 1, incrdown, xloc=xloc.bar_index, extend=extend.both, color=i_psylinescol, width=1, style=line.style_solid)

//?--- Alerts ---?

if sell ? high + atrxy          : na
    alert('Sell Condition! At '              + str.tostring(math.round_to_mintick(close)), alert.freq_once_per_bar)
if buy  ? low  - atrxy          : na
    alert('Buy Condition! At '               + str.tostring(math.round_to_mintick(close)), alert.freq_once_per_bar)
if shortcr     ? (high) + atrxy : na
    alert('Sell Continuity/Reversal! At '    + str.tostring(math.round_to_mintick(close)), alert.freq_once_per_bar)
if longcr      ? (low)  - atrxy : na
    alert('Buy Continuity/Reversal! At '     + str.tostring(math.round_to_mintick(close)), alert.freq_once_per_bar)
if i_showkjhlabels or i_showkjhsr and hiddenbearkj == 1
    alert('Hidden Kijun Resistance! At '     + str.tostring(math.round_to_mintick(close)), alert.freq_once_per_bar)
if i_showkjhlabels or i_showkjhsr and hiddenbullkj == 1
    alert('Hidden Kijun Support! At '        + str.tostring(math.round_to_mintick(close)), alert.freq_once_per_bar)
if i_showtable and table_downtrend
    alert('Panel : Bearish Trend! At '       + str.tostring(math.round_to_mintick(close)), alert.freq_once_per_bar)
if i_showtable and table_uptrend
    alert('Panel : Bullish Trend! At '       + str.tostring(math.round_to_mintick(close)), alert.freq_once_per_bar)
if i_showtable and table_consolidation
    alert('Panel : Trend Consolidation! At ' + str.tostring(math.round_to_mintick(close)), alert.freq_once_per_bar)



// // Purpose: Draws an "Open High Low Close" type visual on an intraday chart to the right of the current price action. 
// //          This visual allows the trader to easily see the current days/weeks range and when it opened and it's current close.
// //          This visual allows the trader to easily indentify Power 3 conceps created by the Inner Circle Trader (ICT) - Accumulation, Manipulation, & Distribution


// // Usage: Switch between drawing Daily or Weekly range
// //        Ability to move the Visual to the right of the current candles. Lines: user has option to change the lines color, style, and width.
// //        Independently toggle ON/OFF the Power 3 labels (Accumulation, Manipulation, Range Extension, Distribution) and can change labels color.
// //        Labels dynamically move and switch positions based upon bear or bull daily/weekly range.


// // Note: this indicator is intended for use in the Futures Market

// // Note 2: when the chart timeframe is 12hr, 4hr, 2hr the horizontal lines can appear unproportial because of Market closed times

// // Update 1: added option in Settings to draw left side horizontal line either at the midngiht EST open or daily open


// ///////////////////////////////////////////////////////////////////////////////// INPUTS


// var string GP3 = "Power 3 Visual"
// i_label_toggle = input.bool(defval=true, title="", group=GP3, inline="labels")
// i_label_text_color = input.color(defval=color.rgb(255, 255, 255, 0), title="Display Labels", group=GP3, inline="labels")
// c_tooltip_timeframe = "Switch the Power 3 Visual between the current Day or current Week"
// i_timeframe = input.timeframe(defval="W", title="Timeframe", options=["D", "W"], group=GP3, tooltip=c_tooltip_timeframe)
// i_daily_start = input.timeframe(defval="Midnight", title="Daily Start", options=["Open", "Midnight"], group=GP3, tooltip="Pick either Daily open price or Midnight EST open price")
// c_tooltip_move = "The Futures market is open 23/5. It is closed everyday for 1-hour at 5pm EST and closed over the weekends. Because this Intraday Power 3 Visual is drawing in the 'future' on the users TradingView chart, when the visual is close or in a time when the market is closed, the visual doesn't behave properly. This is because TradingView doesn't display times when the Market is closed, thus the drawings cannot be displayed during those times. There is nothing wrong with the script. Please wait until the Market is open and the visual will be drawn normally."
// i_right_movement = input.int(defval=5, minval=1, step=1, title="Visual Right Movement", group=GP3, tooltip=c_tooltip_move)
// i_line_color = input.color(defval=color.rgb(255, 255, 255, 0), title="Line Color", group=GP3) 
// i_line_width = input.int(defval=2, minval=1, maxval=20, step=1, title="Line Width", group=GP3)
// i_line_style = input.string(defval="solid (-)", title="Line Style", options=["solid (-)", "dotted (?)", "dashed (?)"], group=GP3)


// ///////////////////////////////////////////////////////////////////////////////// HELPER FUNCTIONS


// // Function the converts string inputs to line style code
// line_style_function(input_var) =>
//     switch input_var
//         "dotted (?)" => line.style_dotted
//         "dashed (?)" => line.style_dashed
//         => line.style_solid


// ///////////////////////////////////////////////////////////////////////////////// TIMEFRAME


// timeframe_high = request.security(syminfo.tickerid, i_timeframe, high)
// timeframe_low = request.security(syminfo.tickerid, i_timeframe, low)
// timeframe_open_req = request.security(syminfo.tickerid, i_timeframe, open)
// timeframe_close = request.security(syminfo.tickerid, i_timeframe, close)

// // Logic for midnight est open or daily open 

// // Time variables
// midnight_window = (hour(time, "America/New_York") == 0) and (minute(time) == 0)
// midnight_timespan_est = time(timeframe.period, '0001-1659', "America/New_York")

// var float midnight_open = na
// var float timeframe_open = na


// if i_timeframe == "W"
//     timeframe_open := timeframe_open_req
// else
//     // Timeframe set to daily
    
//     if i_daily_start == "Open"
//         timeframe_open := timeframe_open_req
//     else
    
//         // Get price at midnight open EST
//         if midnight_window
//             midnight_open := open
        
//         // If time is after midnight est then use midnight price, if price before midnight price then use daily open price
//         if midnight_timespan_est
//             timeframe_open := midnight_open
//         else
//             timeframe_open := timeframe_open_req

// ///////////////////////////////////////////////////////////////////////////////// BULL & BEAR VARIABLES

// var float manipulation_value = na
// var float distribution_value = na
// range_explansion_value = (timeframe_open + timeframe_close) / 2


// // Sets values based on whether daily/weekly range is bear or bull direction
// if timeframe_open > timeframe_close
//     // Bearish candle
//     manipulation_value := (timeframe_open + timeframe_high) / 2
//     distribution_value := (timeframe_close + timeframe_low) / 2
// else
//     // Bullish candle
//     manipulation_value := (timeframe_open + timeframe_low) / 2
//     distribution_value := (timeframe_close + timeframe_high) / 2

// ///////////////////////////////////////////////////////////////////////////////// POWER 3 VISUAL

// // Move timebased labels right
// dt = time + i_right_movement * (time - time[1])
// dt_current = time + (i_right_movement * 2) * (time - time[1])

// // Visual line style
// line_style_power3 = line_style_function(i_line_style)

// // Set defaults for all lines and labels
// var line line_vertical = na
// var line line_power3_open = na
// var line line_power3_current = na
// var label label_range_expansion = na
// var label label_accumulation = na
// var label label_manipulation = na
// var label label_distribution = na

// // Saves TradingView resources by only drawing the visual once
// if timeframe.isintraday and barstate.islast
//     // Draw Power 3 lines
    
//     // Vertical line
//     line_vertical := line.new(x1=dt, y1=timeframe_high, x2=dt, y2=timeframe_low, xloc=xloc.bar_time, color=i_line_color, style=line_style_power3, width=i_line_width)
//     line.delete(line_vertical[1])
//     // Left horizontal line
//     line_power3_open := line.new(x1=time, y1=timeframe_open, x2=dt, y2=timeframe_open, xloc=xloc.bar_time, color=i_line_color, style=line_style_power3, width=i_line_width)
//     line.delete(line_power3_open[1])
//     // Right horizontal line
//     line_power3_current := line.new(x1=dt, y1=timeframe_close, x2=dt_current, y2=timeframe_close, xloc=xloc.bar_time, color=i_line_color, style=line_style_power3, width=i_line_width)
//     line.delete(line_power3_current[1])

//     // Toggle on/off lables
//     if i_label_toggle
//         // Place labels
        
//         // Range Expanseion label
//         label_range_expansion := label.new(x=dt, y=range_explansion_value, text="Range Expansion", xloc=xloc.bar_time, style=label.style_none, textcolor=i_label_text_color, textalign=text.align_center, tooltip="Range Expansion is ...")
//         label.delete(label_range_expansion[1])
//         // Accumulation label
//         label_accumulation := label.new(x=dt, y=timeframe_open, text="Accumulation", xloc=xloc.bar_time, style=label.style_none, textcolor=i_label_text_color, textalign=text.align_right, tooltip="Accumulation is ...")
//         label.delete(label_accumulation[1])
//         // Manipulation label
//         label_manipulation := label.new(x=dt, y=manipulation_value, text="Manipulation", xloc=xloc.bar_time, style=label.style_none, textcolor=i_label_text_color, textalign=text.align_center, tooltip="Manipulation is ...")
//         label.delete(label_manipulation[1])
//         // Distribution label
//         label_distribution := label.new(x=dt, y=distribution_value, text="Distribution", xloc=xloc.bar_time, style=label.style_none, textcolor=i_label_text_color, textalign=text.align_center, tooltip="Distribution is ...")
//         label.delete(label_distribution[1])  


 
//===========================================================================================================//

 // choppp filter////////


show_chop = input.bool(true, "Show")
cae_len = input.int(14, minval=1, title="Length", inline="cae1")
cae_src = input.source(close, "Source", inline="cae1")
ch_ut=input.float(60.0, "Choppy Range Thresholds: Upper", inline = "choppy1") 
ch_lt=input.float(40.0, "Lower", inline = "choppy1")

bout_circ=input.bool(true,"Break-Out Circles",inline="choppy2")
bin_cross=input.bool(true,"Break-In Crosses <- Choppy Range",inline="choppy2")

buy_alerts = input.bool(true,"Buy", inline="caeal")
sell_alerts = input.bool(true,"Sell", inline="caeal")
choppy_alerts = input.bool(true,"Choppy <- Alerts", inline="caeal")


//User has to agree to have the indi loading on the chart.
//var user_consensus = input.string(default="", title="TYPE 'agree' TO ADD TO CHART. \nTrading involves a risk of loss, and may not be appropriate for every one. Please consider carefully if trading is appropriate for you. Past performance is not indicative of future results. Any and all indicator signals provided by 'MM Chop And Explode Chart' are for educational purposes only. Is your responsibility knowing that by typing 'agree' you are accepting that the AI would trade on your behalf at your own risk. \nRELEASE INFORMATION 2021  Money Moves Investments", confirm = true, group="consensus")
var icc = true
// if user_consensus == "agree"
//     icc := true
// else
//     icc := false


cae_up = ta.rma(math.max(ta.change(cae_src), 0), cae_len)
cae_down = ta.rma(-math.min(ta.change(cae_src), 0), cae_len)
cae_rsi = cae_down == 0 ? 100 : cae_up == 0 ? 0 : 100 - (100 / (1 + cae_up / cae_down))

var is_chop = false
var float chop_beg_h = na
var float chop_beg_l = na
var box chop_box = na

var chop_cond = false
chop_cond:= cae_rsi >= ch_lt and cae_rsi <= ch_ut

if chop_cond and not is_chop[1]
    is_chop := true
    chop_beg_h:=high
    chop_beg_l:=low
    chop_box := icc and show_chop? box.new(bar_index, chop_beg_h, bar_index, chop_beg_l, bgcolor=color.new(color.orange,80), border_color=color.black):na
else if chop_cond and is_chop[1] and is_chop
    box.set_right(chop_box, bar_index)
    if high>chop_beg_h
        box.set_top(chop_box, high)
        chop_beg_h:=high
    if low<chop_beg_l
        box.set_bottom(chop_box,low)
        chop_beg_l:=low
else
    is_chop:=false
    chop_beg_h:=0.0
    chop_beg_l:=0.0


choppy_bup = ta.crossover(cae_rsi, ch_ut)
choppy_bdown = ta.crossunder(cae_rsi, ch_lt)

up_to_choppy = ta.crossunder(cae_rsi, ch_ut)
down_to_choppy = ta.crossover(cae_rsi, ch_lt)

alertcondition(icc and choppy_bup and buy_alerts, "BUY", "Choppy Range Break-up")
alertcondition(icc and choppy_bdown and sell_alerts, "SELL", "Choppy Range Break-down")
alertcondition(icc and up_to_choppy and choppy_alerts, "BUY EXIT", "Got inside Choppy Range")
alertcondition(icc and down_to_choppy and choppy_alerts, "SELL EXIT", "Got inside Choppy Range")

// plotshape(icc and choppy_bup and bout_circ, title="Choppy Range Break-ups",style=shape.circle,location=location.belowbar,color=color.aqua,size=size.small)
// plotshape(icc and choppy_bdown and bout_circ,title="Choppy Range Break-downs",style=shape.circle,location=location.abovebar,color=color.red,size=size.small)

// plotshape(icc and up_to_choppy and bin_cross, title="Choppy Range Down Break-Ins",style=shape.cross,location=location.abovebar,color=color.aqua)
// plotshape(icc and down_to_choppy and bin_cross,title="Choppy Range Up Break-Ins",style=shape.cross,location=location.belowbar,color=color.red)

//===============================================================================================================//


res = input.timeframe(defval='D')


dayrange = high - low
r1r = request.security(syminfo.tickerid, res, dayrange[1])
r2r = request.security(syminfo.tickerid, res, dayrange[2])
r3 = request.security(syminfo.tickerid, res, dayrange[3])
r4 = request.security(syminfo.tickerid, res, dayrange[4])
r5 = request.security(syminfo.tickerid, res, dayrange[5])
r6 = request.security(syminfo.tickerid, res, dayrange[6])
r7 = request.security(syminfo.tickerid, res, dayrange[7])
r8 = request.security(syminfo.tickerid, res, dayrange[8])
r9 = request.security(syminfo.tickerid, res, dayrange[9])
r10 = request.security(syminfo.tickerid, res, dayrange[10])
r11 = request.security(syminfo.tickerid, res, dayrange[11])
r12 = request.security(syminfo.tickerid, res, dayrange[12])
oo = request.security(syminfo.tickerid, res, open, barmerge.gaps_off, barmerge.lookahead_on)
zone1 = oo + (r1r + r2r + r3 + r4 + r5) / 10
zone2 = oo + (r1r + r2r + r3 + r4 + r5 + r6 + r7 + r8 + r9 + r10) / 10 / 2
zone3 = oo - (r1r + r2r + r3 + r4 + r5) / 10
zone4 = oo - (r1r + r2r + r3 + r4 + r5 + r6 + r7 + r8 + r9 + r10) / 10 / 2

// r1=security(syminfo.tickerid,res,dayrange, barmerge.gaps_off, barmerge.lookahead_on)
// r2=security(syminfo.tickerid,res,dayrange, barmerge.gaps_off, barmerge.lookahead_on)
// r3=security(syminfo.tickerid,res,dayrange, barmerge.gaps_off, barmerge.lookahead_on)
// r4=security(syminfo.tickerid,res,dayrange, barmerge.gaps_off, barmerge.lookahead_on)
// r5=security(syminfo.tickerid,res,dayrange, barmerge.gaps_off, barmerge.lookahead_on)
// r6=security(syminfo.tickerid,res,dayrange, barmerge.gaps_off, barmerge.lookahead_on)
// r7=security(syminfo.tickerid,res,dayrange, barmerge.gaps_off, barmerge.lookahead_on)
// r8=security(syminfo.tickerid,res,dayrange, barmerge.gaps_off, barmerge.lookahead_on)
// r9=security(syminfo.tickerid,res,dayrange, barmerge.gaps_off, barmerge.lookahead_on)
// r10=security(syminfo.tickerid,res,dayrange, barmerge.gaps_off, barmerge.lookahead_on)

// oo = security(syminfo.tickerid, res, open ,barmerge.gaps_off, barmerge.lookahead_on)
// zone1= oo + ( r1 +r2 +r3 +r4 +r5 )/5/2
// zone2= oo + ( r1 +r2 +r3 +r4+r5+r6+r7 +r8+r9+r10)/10/2
// zone3= oo - ( r1 +r2 +r3 +r4 +r5 )/5/2
// zone4 = oo- ( r1 +r2 +r3 +r4+r5+r6+r7 +r8+r9+r10)/10/2
z1 = plot(zone1, title='Z1', color=color.new(color.green, 0), linewidth=1, style=plot.style_line)
z2 = plot(zone2, title='Z2', color=color.new(color.green, 0), linewidth=1, style=plot.style_line)
z3 = plot(zone3, title='Z3', color=color.new(color.red, 0), linewidth=1, style=plot.style_line)
z4 = plot(zone4, title='Z4', color=color.new(color.red, 0), linewidth=1, style=plot.style_line)


fill(z1, z2, color=color.new(color.green, 50))
fill(z3, z4, color=color.new(color.red, 50))

buycondition = ta.crossover(close, zone2)
sellcondition = ta.crossunder(close, zone4)
alertcondition(buycondition or sellcondition, title='Alert for buy and sell ', message='You got alert from zone indicator : {{exchange}}:{{ticker}}, Price = {{close}}, Volume = {{volume}}')

//=========================================================================//


// INPUTS
Resolution = input.timeframe('', 'Resolution')  // Choose timeframe for baseline ema
Show_Ma = input(false, 'Show moving average')
Repaint = input(false, 'Repaint ?')

Type = input.string('Donchian', 'Type', options=['SMA', 'EMA', 'HMA', 'RMA', 'WMA', 'VWMA', 'ALMA', 'Donchian']) //select MA type
Length = input.int(30, 'Length', minval=1)
ALMA_Offset = 0.85
ALMA_Sigma = 6

Strategy = input.string('CLOSE', 'Closing Strategy', options=['OHLC4', 'HLC3', 'HL2', 'CLOSE'])

Signals = input(true, 'Show signals')
Bars = input(false, 'Show barcolor')
Background = input(false, 'Show Background')
Fill = input(false, 'Fill baseline')

// SETTINGS
O = Repaint ? open : open[1]
H = Repaint ? high : high[1]
L = Repaint ? low : low[1]
C = Repaint ? close : close[1]
OHLC = Repaint ? ohlc4 : ohlc4[1]
HLC = Repaint ? hlc3 : hlc3[1]
HL = Repaint ? hl2 : hl2[1]

OPEN = request.security(syminfo.tickerid, Resolution, O)
HIGH = request.security(syminfo.tickerid, Resolution, H)
LOW = request.security(syminfo.tickerid, Resolution, L)
CLOSE = request.security(syminfo.tickerid, Resolution, C)
OHLC4 = request.security(syminfo.tickerid, Resolution, OHLC)
HLC3 = request.security(syminfo.tickerid, Resolution, HLC)
HL2 = request.security(syminfo.tickerid, Resolution, HL)

Average_ = Type == 'SMA' ? ta.sma(CLOSE, Length) : Type == 'EMA' ? ta.ema(CLOSE, Length) : Type == 'HMA' ? ta.hma(CLOSE, Length) : Type == 'RMA' ? ta.rma(CLOSE, Length) : Type == 'WMA' ? ta.wma(CLOSE, Length) : Type == 'VWMA' ? ta.vwma(CLOSE, Length) : Type == 'ALMA' ? ta.alma(CLOSE, Length, ALMA_Offset, ALMA_Sigma) : Type == 'Donchian' ? math.avg(ta.highest(CLOSE, Length), ta.lowest(CLOSE, Length)) : na

Upper_ = Type == 'SMA' ? ta.sma(HIGH, Length) : Type == 'EMA' ? ta.ema(HIGH, Length) : Type == 'HMA' ? ta.hma(HIGH, Length) : Type == 'RMA' ? ta.rma(HIGH, Length) : Type == 'WMA' ? ta.wma(HIGH, Length) : Type == 'VWMA' ? ta.vwma(HIGH, Length) : Type == 'ALMA' ? ta.alma(HIGH, Length, ALMA_Offset, ALMA_Sigma) : Type == 'Donchian' ? math.avg(ta.highest(HIGH, Length), ta.lowest(HIGH, Length)) : na

Lower_ = Type == 'SMA' ? ta.sma(LOW, Length) : Type == 'EMA' ? ta.ema(LOW, Length) : Type == 'HMA' ? ta.hma(LOW, Length) : Type == 'RMA' ? ta.rma(LOW, Length) : Type == 'WMA' ? ta.wma(LOW, Length) : Type == 'VWMA' ? ta.vwma(LOW, Length) : Type == 'ALMA' ? ta.alma(LOW, Length, ALMA_Offset, ALMA_Sigma) : Type == 'Donchian' ? math.avg(ta.highest(LOW, Length), ta.lowest(LOW, Length)) : na

Average = request.security(syminfo.tickerid, Resolution, Average_)
Upper = request.security(syminfo.tickerid, Resolution, Upper_)
Lower = request.security(syminfo.tickerid, Resolution, Lower_)

H_Set = Strategy == 'OHLC4' ? OHLC4 : Strategy == 'HLC3' ? HLC3 : Strategy == 'HL2' ? HL2 : Strategy == 'CLOSE' ? CLOSE : na
L_Set = Strategy == 'OHLC4' ? OHLC4 : Strategy == 'HLC3' ? HLC3 : Strategy == 'HL2' ? HL2 : Strategy == 'CLOSE' ? CLOSE : na

Dir_1 = float(na)
Dir_1 := L_Set > Upper ? 1 : H_Set < Lower ? -1 : nz(Dir_1[1])
Up_Sig = Dir_1 != Dir_1[1] and Dir_1 == 1 and Signals
Dn_Sig = Dir_1 != Dir_1[1] and Dir_1 == -1 and Signals
Color_1_1 = Dir_1 == 1 ? close > open ? color.new(#a5d6a7, 0) : color.new(#81c784, 0) : close > open ? color.new(#ef9a9a, 0) : color.new(#e57373, 0)
Color_1_2 = Dir_1 == 1 ? color.new(#4caf50, 80) : color.new(#f44336, 80)

Dir_2 = float(na)
Dir_2 := Average > Average[1] ? 1 : Average < Average[1] ? -1 : nz(Dir_2[1])
Color_2 = Dir_2 == 1 ? color.new(#000000, 1) : color.new(#000000, 0)

Color_3 = Fill ? color.new(#000000, 90) : color.new(#000000, 100)

// PLOT
plot(Show_Ma ? Average : na, 'Moving Average', Color_2, 2)

P1 = plot(Upper, 'Upper Line', Color_2, 2)
P2 = plot(Lower, 'Upper Line', Color_2, 2)
fill(P1, P2, title='Baseline Fill', color=Color_3)

plotshape(Up_Sig ? Lower : na, 'Buy', color=color.new(#00ff00, 40), location=location.absolute, size=size.small, style=shape.labelup, text='Buy', textcolor=color.new(#000000, 0))
plotshape(Dn_Sig ? Upper : na, 'Sell', color=color.new(#ff0000, 40), location=location.absolute, size=size.small, style=shape.labeldown, text='Sell', textcolor=color.new(#ffffff, 0))

barcolor(Bars ? Color_1_1 : na, title='Bar Color')
bgcolor(Background ? Color_1_2 : na, title='Background', transp=90)

// ALERT
alertcondition(Dir_1 != Dir_1[1] and Dir_1 == 1, 'UpTrend', 'UpTrend Triggered!')
alertcondition(Dir_1 != Dir_1[1] and Dir_1 == -1, 'DownTrend', 'DownTrend Triggered!')
alertcondition(Dir_1 != Dir_1[1], 'Trend Changed', 'Trend Changed!')



//Interior
ben0 = input('CRYPTOCAP:BTC', 'Benchmark-CRYPTOCAP:BTC,NSE:NIFTY')      //NSE:NIFTY  //choose according to market
src0 = input(hlc3, 'Source')
len0 = input(9, 'Channel Length')
len1 = input(26, 'Average Length')
len2 = input(13, 'Short length')
cou0 = input(5, 'Count')
smo0 = input(false, 'Smoothing')

//Engine
security_1 = request.security(ben0, timeframe.period, src0)
security_2 = request.security(syminfo.tickerid, timeframe.period, src0)
src1 = ben0 != syminfo.tickerid ? security_1 : security_2

ttsi(_src, _len0, _len1) =>
    pc = ta.change(_src) / math.avg(_src, _src[1])
    ma0 = ta.ema(pc, _len0)
    ma1 = ta.ema(ma0, _len1)
    apc = math.abs(_src - _src[1])
    ma2 = ta.ema(apc, _len0)
    ma3 = ta.ema(ma2, _len1)
    ttsi = 100 * (ma1 / ma3)
    ttsi

tci(_src) =>
    ta.ema((_src - ta.ema(_src, len0)) / (0.025 * ta.ema(math.abs(_src - ta.ema(_src, len0)), len0)), len1) + 50

mf(_src) =>
    100.0 - 100.0 / (1.0 + math.sum(volume * (ta.change(_src) <= 0 ? 0 : _src), len2) / math.sum(volume * (ta.change(_src) >= 0 ? 0 : _src), len2))

willy(_src) =>
    60 * (_src - ta.highest(_src, len1)) / (ta.highest(_src, len1) - ta.lowest(_src, len1)) + 80

csi(_src) =>
    math.avg(ta.rsi(_src, len2), ttsi(_src, len0, len1) * 50 + 50)

godmode(_src) =>
    math.avg(tci(_src), csi(_src), mf(_src), willy(_src))

tradition(_src) =>
    math.avg(tci(_src), mf(_src), ta.rsi(_src, len2))

godmode__1 = godmode(src1)
tradition__1 = tradition(src1)
wt0 = ben0 != syminfo.tickerid ? godmode__1 : tradition__1
swt0 = ta.sma(wt0, len0)

gm = smo0 ? swt0 : wt0

gr = 0
incrementer_up = gm > 70 ? 1 : 0
if incrementer_up
    gr := nz(gr[1], 0) + incrementer_up
    gr
else
    gr = 0
    gr
grH = if gr >= cou0
    x = high
    x
grL = if gr >= cou0
    y = low
    y
grh = fixnan(grH)
grl = fixnan(grL)

gs = 0
incrementer_down = gm < 30 ? 1 : 0
if incrementer_down
    gs := nz(gs[1], 0) + incrementer_down
    gs
else
    gs = 0
    gs
gsH = if gs >= cou0
    x = high
    x
gsL = if gs >= cou0
    y = low
    y
gsh = fixnan(gsH)
gsl = fixnan(gsL)

gsdx = 0
incrementer_both = gm > 70 or gm < 30 ? 1 : 0
if incrementer_both
    gsdx := nz(gsdx[1], 0) + incrementer_both
    gsdx
else
    gsdx = 0
    gsdx
gsdH = if gsdx >= cou0
    x = high
    x
gsdL = if gsdx >= cou0
    y = low
    y
gsdh = fixnan(gsdH)
gsdl = fixnan(gsdL)

//Chassis
p1 = plot(gsh, 'High Support', color.new(color.lime, 0), 1, plot.style_circles)
p2 = plot(gsl, 'Low Support', color.new(color.green, 0), 1, plot.style_circles)
p3 = plot(grh, 'High Resistance', color.new(color.red, 0), 1, plot.style_circles)
p4 = plot(grl, 'Low Resistance', color.new(color.fuchsia, 0), 1, plot.style_circles)
p5 = plot(gsdh, 'High Supply Above/Demand Below', color.new(color.orange, 0), 1, plot.style_circles) //helps u with supply and demand zone
p6 = plot(gsdl, 'Low Supply Above/Demand Below', color.new(color.yellow, 0), 1, plot.style_circles)

fill(p1, p2, color.new(color.olive, 90))
fill(p3, p4, color.new(color.maroon, 90))
fill(p5, p6, color.new(color.blue, 90))





//==================================================================================================//


src = input(defval=close, title='Source')
len22 = input.int(defval=100, title='Length', minval=10)
devlen = input.float(defval=2., title='Deviation', minval=0.1, step=0.1)
extendit = input(defval=true, title='Extend Lines')
showfibo = input(defval=false, title='Show Fibonacci Levels')
showbroken = input.bool(defval=true, title='Show Broken Channel', inline='brk')
brokencol = input.color(defval=color.blue, title='', inline='brk')
upcol2 = input.color(defval=color.lime, title='Up/Down Trend Colors', inline='trcols')
dncol2 = input.color(defval=color.red, title='', inline='trcols')
widt = input(defval=2, title='Line Width')

var fibo_ratios = array.new_float(0)
var colors = array.new_color(2)
if barstate.isfirst
    array.unshift(colors, upcol2)
    array.unshift(colors, dncol2)
    array.push(fibo_ratios, 0.236)
    array.push(fibo_ratios, 0.382)
    array.push(fibo_ratios, 0.618)
    array.push(fibo_ratios, 0.786)


get_channel(src, len22) =>
    mid = math.sum(src, len22) / len22
    slope = ta.linreg(src, len22, 0) - ta.linreg(src, len22, 1)
    intercept = mid - slope * math.floor(len22 / 2) + (1 - len22 % 2) / 2 * slope
    endy = intercept + slope * (len22 - 1)
    dev = 0.0
    for x = 0 to len22 - 1 by 1
        dev += math.pow(src[x] - (slope * (len22 - x) + intercept), 2)
        dev
    dev := math.sqrt(dev / len22)
    [intercept, endy, dev, slope]

[y1_, y2_, dev, slope] = get_channel(src, len22)

outofchannel = slope > 0 and close < y2_ - dev * devlen ? 0 : slope < 0 and close > y2_ + dev * devlen ? 2 : -1

var reglines = array.new_line(3)
var fibolines = array.new_line(4)
for x = 0 to 2 by 1
    if not showbroken or outofchannel != x or nz(outofchannel[1], -1) != -1
        line.delete(array.get(reglines, x))
    else
        line.set_color(array.get(reglines, x), color=brokencol)
        line.set_width(array.get(reglines, x), width=2)
        line.set_style(array.get(reglines, x), style=line.style_dotted)
        line.set_extend(array.get(reglines, x), extend=extend.none)

    array.set(reglines, x, line.new(x1=bar_index - (len22 - 1), y1=y1_ + dev * devlen * (x - 1), x2=bar_index, y2=y2_ + dev * devlen * (x - 1), color=array.get(colors, math.round(math.max(math.sign(slope), 0))), style=x % 2 == 1 ? line.style_solid : line.style_dashed, width=widt, extend=extendit ? extend.right : extend.none))
if showfibo
    for x = 0 to 3 by 1
        line.delete(array.get(fibolines, x))
        array.set(fibolines, x, line.new(x1=bar_index - (len22 - 1), y1=y1_ - dev * devlen + dev * devlen * 2 * array.get(fibo_ratios, x), x2=bar_index, y2=y2_ - dev * devlen + dev * devlen * 2 * array.get(fibo_ratios, x), color=array.get(colors, math.round(math.max(math.sign(slope), 0))), style=line.style_dotted, width=widt, extend=extendit ? extend.right : extend.none))

var label sidelab = label.new(x=bar_index - (len22 - 1), y=y1_, text='S', size=size.large)
txt = slope > 0 ? slope > slope[1] ? '?' : '?' : slope < 0 ? slope < slope[1] ? '?' : '?' : '?'
stl = slope > 0 ? slope > slope[1] ? label.style_label_up : label.style_label_upper_right : slope < 0 ? slope < slope[1] ? label.style_label_down : label.style_label_lower_right : label.style_label_right
label.set_style(sidelab, stl)
label.set_text(sidelab, txt)
label.set_x(sidelab, bar_index - (len22 - 1))
label.set_y(sidelab, slope > 0 ? y1_ - dev * devlen : slope < 0 ? y1_ + dev * devlen : y1_)
label.set_color(sidelab, slope > 0 ? upcol2 : slope < 0 ? dncol2 : color.blue)

alertcondition(outofchannel, title='Channel Broken', message='Channel Broken')

// direction
trendisup = math.sign(slope) != math.sign(slope[1]) and slope > 0
trendisdown = math.sign(slope) != math.sign(slope[1]) and slope < 0
alertcondition(trendisup, title='Up trend', message='Up trend')
alertcondition(trendisdown, title='Down trend', message='Down trend')

//indicator(title="Moving Average Exponential", shorttitle="EMA", overlay=true, timeframe="", timeframe_gaps=true)
len = input.int(200, minval=1, title="Length")
//src = input(close, title="Source")
offset = input.int(title="Offset", defval=0, minval=-500, maxval=500)
out = ta.ema(src, len)
plot(out, title="EMA", color=color.red, offset=offset)

ma(source, length, type) =>
    switch type
        "SMA" => ta.sma(source, length)
        "EMA" => ta.ema(source, length)
        "SMMA (RMA)" => ta.rma(source, length)
        "WMA" => ta.wma(source, length)
        "VWMA" => ta.vwma(source, length)

typeMA = input.string(title = "Method", defval = "SMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Smoothing")
smoothingLength = input.int(title = "Length", defval = 5, minval = 1, maxval = 100, group="Smoothing")

smoothingLine = ma(out, smoothingLength, typeMA)
plot(smoothingLine, title="Smoothing Line", color=#f37f20, offset=offset, display=display.none)